package ord2.core;

import java.util.HashMap;

/**
 * This class represents a abstract factory with implemented common operations.
 *
 * @author José Ivan
 * @author Edviges
 *
 * @param <K> Type of object that is used to maps a instance
 * @param <V> Type of object instances that are carried by this factory
 */
public class AbstractFactory<K, V> implements Factory<K, V> {
    
    private HashMap<K, V> attachedInstances = new HashMap<K, V>();

    /**
     * Attaches a instance to this factory with a key that will be used to retrieve
     * this instance.
     * @param key Key to attach a instance
     * @param value Object that will be attached
     * @return always true
     * @throws NullPointerException if key or value are null
     */
    @Override
    public boolean attachInstance(K key, V value) {
        
        if (key == null || value == null) {
            
            throw new NullPointerException("key and value must not be null.");
        }
        
        this.attachedInstances.put(key, value);
        
        return true;
    }

    @Override
    public V getAttachedInstance(K key) {
        
        return this.attachedInstances.get(key);
    }

    @Override
    @SuppressWarnings("unchecked")
    public V[] getAllAttachedInstances() {
        
        return (V[]) this.attachedInstances.values().toArray();
    }

    @Override
    @SuppressWarnings("unchecked")
    public K[] getAllKeys() {
        
        return (K[]) this.attachedInstances.keySet().toArray();
    }
}
